package com.hbisedm.interninfosys.listener;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hbisedm.interninfosys.intern.entity.User;
import com.hbisedm.interninfosys.intern.entity.UserRole;
import com.hbisedm.interninfosys.intern.entity.vo.ExcelPersonVo;
import com.hbisedm.interninfosys.intern.service.IUserRoleService;
import com.hbisedm.interninfosys.intern.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class ExcelListener extends AnalysisEventListener<ExcelPersonVo> {

    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private IUserService userService;
    private IUserRoleService userRoleService;
    /**
     * 用户类型
     */
    private Integer type;

    private final static String SEX = "男";

    List<ExcelPersonVo> list = new ArrayList<>();

    public ExcelListener(IUserService userService, IUserRoleService userRoleService, BCryptPasswordEncoder bCryptPasswordEncoder, Integer type) {
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.type = type;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param excelVo
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelPersonVo excelVo, AnalysisContext analysisContext) {
        System.out.println("invoke方法被调用");
        System.out.println(excelVo.toString());
        list.add(excelVo);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("doAfterAllAnalysed方法 被调用");
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        ArrayList<User> users = new ArrayList<>();
        list.stream().forEach(item -> {
//            String pinyin = PinyinUtil.getPinyin(item.getName());
            User user = new User();
            BeanUtils.copyProperties(item, user);
            user.setUsername(item.getUsername().toString());
            if (item.getSex().equals(SEX)) {
                user.setSex(1);
            }else {
                user.setSex(2);
            }
            user.setPassword(bCryptPasswordEncoder.encode("123456"));
            user.setType(type);
            userService.save(user);
            /**
             * 设置普通用户
             */
            UserRole userRole = new UserRole(user.getId(), 2);
            userRoleService.save(userRole);
        });

        userService.saveBatch(users);
        System.out.println("存储数据库成功！");
    }
}
